package cn.zhejianglao.shirotemplate.common.model;

import cn.zhejianglao.shirotemplate.exception.BusinessException;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.StringUtils;

@Data
@NoArgsConstructor
public class Response<T> {

    public static final int SUCCESS_CODE = 0;
    public static final int FAIL_CODE = -1;
    public static final String SUCCESS_MESSAGE = "success";
    private int code;
    private String message;
    private T data;

    public Response(int code, String message) {
        this.code = code;
        this.message = message;
        this.data = null;
    }

    /**
     * generate response based on a business exception
     *
     * @param exception business exception
     * @return response
     */
    public static Response<String> exceptionResponse(BusinessException exception) {
        Response<String> response = new Response<>();
        String message = exception.getMsg();
        if (!StringUtils.isEmpty(message)) {
            response.setMessage(message);
        } else {
            response.setMessage(exception.toString());
        }
        response.setCode(exception.getCode());
        return response;
    }

    public static <T> Response<T> success(T data) {
        Response<T> response = new Response<>();
        response.setCode(SUCCESS_CODE);
        response.setMessage(SUCCESS_MESSAGE);
        response.setData(data);
        return response;
    }

    public static <T> Response<T> success() {
        Response<T> response = new Response<>();
        response.setCode(SUCCESS_CODE);
        response.setMessage(SUCCESS_MESSAGE);
        return response;
    }

    /**
     * 失败
     *
     * @param errorCode 失败码
     * @param errorMsg 失败消息
     * @return 响应体
     */
    public static Response<String> fail(int errorCode, String errorMsg) {
        Response<String> response = new Response<>();
        response.setCode(errorCode);
        response.setMessage(errorMsg);
        return response;
    }

    /**
     * 失败
     *
     * @param errorMsg 失败消息
     * @return 响应体
     */
    public static Response<String> fail(String errorMsg) {
        return fail(FAIL_CODE, errorMsg);
    }
}
